<!-- static/index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>协作编辑器</title>
    <style>
        #editor {
            width: 800px;
            height: 600px;
            border: 1px solid #ccc;
            padding: 10px;
            font-family: monospace;
        }
        .status {
            color: #666;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <h1>协作编辑器</h1>
    <div id="editor" contenteditable="true"></div>
    <div class="status">连接状态：<span id="status">未连接</span></div>

    <script>
        const editor = document.getElementById('editor');
        const statusSpan = document.getElementById('status');
        let ws;
        let lastKnownVersion = 0;
        let isLocalEdit = false;

        function connect() {
            ws = new WebSocket('ws://' + window.location.host + '/ws');
            
            ws.onopen = () => {
                statusSpan.textContent = '已连接';
                statusSpan.style.color = 'green';
            };

            ws.onmessage = (event) => {
                const msg = JSON.parse(event.data);
                switch(msg.type) {
                    case 'INIT':
                        editor.innerHTML = msg.content;
                        lastKnownVersion = msg.version;
                        break;
                    case 'OPERATION':
                        if (msg.version > lastKnownVersion) {
                            isLocalEdit = true;
                            applyRemoteOperation(msg);
                            isLocalEdit = false;
                            lastKnownVersion = msg.version;
                        }
                        break;
                }
            };

            ws.onclose = () => {
                statusSpan.textContent = '已断开';
                statusSpan.style.color = 'red';
                setTimeout(connect, 1000);
            };
        }

        function applyRemoteOperation(op) {
            const selection = window.getSelection();
            const range = selection.getRangeAt(0);
            
            // 保存光标位置
            const originalStart = range.startOffset;
            const originalEnd = range.endOffset;

            // 应用操作
            if (op.type === 'INSERT') {
                editor.innerHTML = 
                    editor.innerHTML.slice(0, op.pos) + 
                    op.content + 
                    editor.innerHTML.slice(op.pos);
            } else if (op.type === 'DELETE') {
                editor.innerHTML = 
                    editor.innerHTML.slice(0, op.pos) + 
                    editor.innerHTML.slice(op.pos + op.content.length);
            }

            // 恢复光标
            const newRange = document.createRange();
            newRange.setStart(selection.anchorNode, originalStart);
            newRange.setEnd(selection.focusNode, originalEnd);
            selection.removeAllRanges();
            selection.addRange(newRange);
        }

        editor.addEventListener('input', (e) => {
            if (isLocalEdit) return;

            const version = Date.now();
            const operation = {
                type: 'INSERT', // 简化处理，实际需要区分插入/删除
                pos: getCaretPosition(),
                content: e.data || '',
                version: version
            };

            lastKnownVersion = version;
            ws.send(JSON.stringify(operation));
        });

        function getCaretPosition() {
            const selection = window.getSelection();
            return selection.anchorOffset;
        }

        // 初始化连接
        connect();
    </script>
</body>
</html>